//
//  IPTableViewController.swift
//  elarc01
//
//  Created by elarc on 16/2/26.
//  Copyright © 2016年 elarc. All rights reserved.
//

import UIKit
import TransitionTreasury
import TransitionAnimation

import AVFoundation

class IPTableViewController: UIViewController,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,ModalTransitionDelegate{
    
    var tr_presentTransition: TRViewControllerTransitionDelegate?
    
//    func modalViewControllerDismiss(callbackData data: AnyObject? = nil) {
//        tr_dismissViewController(completion: {
//            print("Dismiss finished.")
//        })
//    }
    
    var dataArray = []
    let tableView = UITableView()
    
    //tabbar 转场
    
    lazy var gesture: UIPanGestureRecognizer = {
        let gesture = UIPanGestureRecognizer(target: self, action: #selector(IPTableViewController.swipeTransition(_:)))
        return gesture
    }()
    
    func swipeTransition(sender: UIPanGestureRecognizer) {
        switch sender.state {
        case .Began :
            if sender.translationInView(sender.view).x < 0 {
                tabBarController?.tr_selected(1, gesture: sender)
            }
        default : break
        }
    }
    
    var searchViewControllerTransition:SearchViewControllerTransition?
    private let searchBar = UISearchBar()
        override func viewDidLoad() {
        super.viewDidLoad()
        //tabbar 转场
        view.addGestureRecognizer(gesture)
            
        tableView.backgroundColor = UIColor.randomColor()
        tableView.tableFooterView = UIView()
        tableView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight-108)
        view.addSubview(tableView)
        
            
        searchViewControllerTransition = SearchViewControllerTransition()
   
        searchBar.frame = CGRectMake(0, 0, ScreenWidth - 80, 46)
        searchBar.barStyle = UIBarStyle.Default
        searchBar.layer.borderWidth = 1
        searchBar.layer.borderColor = UIColor.randomColor().CGColor
        searchBar.placeholder = "搜索"
        searchBar.barTintColor = UIColor.randomColor()
        searchBar.delegate = self
        navigationItem.titleView = UIView(frame:  CGRectMake(40, 0, ScreenWidth - 80, 46))
        self.navigationItem.titleView!.addSubview(searchBar)
        tableView.dataSource = self
        tableView.delegate = self
        
        buildTableViewheader()
        loadData()
        pullToBounsSetting()
      
        //导航栏隐藏1
            //设置当有导航栏自动添加64的高度的属性为NO
            self.automaticallyAdjustsScrollViewInsets = false
            self.setKeyScrollView(tableView, scrolOffsetY: 600, options: ElarcHidenControlOptions.ElarcHidenControlOptionsLeft)
            
    }
    //PullTobounds
    
    func pullToBounsSetting(){
        self.view.backgroundColor = UIColor.blueColor()
        let bodyView = UIView()
        bodyView.frame = self.view.frame
        bodyView.y += 20 + 44
        self.view.addSubview(bodyView)

        //🌟 Usage
        let tableViewWrapper = PullToBounceWrapper(scrollView: tableView)
        bodyView.addSubview(tableViewWrapper)
        
        tableViewWrapper.didPullToRefresh = {
            NSTimer.schedule(delay: 2) { timer in
                tableViewWrapper.stopLoadingAnimation()
            }
        }
    }

    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }

    func loadData() {
        dataArray = ["转场","StickyCollectionView","push","hideNavBar","滑动透明Nav","瀑布流","图表","标签cloud","CoreText","折叠cell","pageControl","switch","pickerView","BubbleModal","parallax","打印","FaceDetectVc","二维码扫描","计步器","someTest"]
        tableView.reloadData()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

     func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return dataArray.count
    }
    
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellId = "Cell"
        let ordinaryCell = UITableViewCell(style: .Value1, reuseIdentifier: cellId)
        ordinaryCell.selectionStyle = UITableViewCellSelectionStyle.None
        ordinaryCell.accessoryType = .DisclosureIndicator
        ordinaryCell.textLabel?.text = dataArray[indexPath.row] as? String
        ordinaryCell.backgroundColor = UIColor.randomColor()
        
        //预加载
//        if indexPath.row == self.sourceArray.count - kNumberOfPerPage/2{
//            loadData()
//            self.specialTopicTableView.footer.beginRefreshing()
//        }
        
        return ordinaryCell
    }
    
     func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
        clickPushTo(indexPath.row)
        
    }
    
    func clickPushTo(row:Int){
        switch row {
        case 0:
           let firstTransVc = FirstTranslasionVC()
           
           self.navigationController?.pushViewController(firstTransVc, animated: true)
        case 1:
            let segement = WelcomeViewController()
            self.navigationController?.pushViewController(segement, animated: true)
            
        case 2:
            let firstTransVc = SecondTranslasionVC()
            
            let updateTransition: TRPushTransitionMethod = .Page
            
            navigationController?.tr_pushViewController(firstTransVc, method: updateTransition, statusBarStyle: .LightContent, completion: {
            })
            
        case 3:
            
           let hideNavBarVc =  HideNavWebVC()
           self.navigationController?.pushViewController(hideNavBarVc, animated: true)
            
        case 4:
            
            let hideNavBarVc =  SecondTranslasionVC()
            hideNavBarVc.title = "滑动"
            self.navigationController?.pushViewController(hideNavBarVc, animated: true)
        case 5:
            let Waterfall =  WaterfallViewController()
            Waterfall.title = "Waterfall"
            self.navigationController?.pushViewController(Waterfall, animated: true)
        case 6:
            let Chart =  ChartViewController()
            Chart.title = "Chart"
            self.navigationController?.pushViewController(Chart, animated: true)
        case 7:
            let cloudTags = CloudTagsViewController()
            cloudTags.title = "标签云"
            self.navigationController?.pushViewController(cloudTags, animated: true)
        case 8:
            let CTVC = CTTestViewController()
            CTVC.title = "coreText"
            self.navigationController?.pushViewController(CTVC, animated: true)
        case 9:
            let foldingCell = FoldingTableViewController()
            foldingCell.title = "foldingCell"
            self.navigationController?.pushViewController(foldingCell, animated: true)
        case 10:
            let pageControl = PageContrlTestVC()
            pageControl.title = "pageControl"
            self.navigationController?.pushViewController(pageControl, animated: true)
        case 11:
            let  switchTest = ElarcSwitchTestController()
            switchTest.title = "switch"
            self.navigationController?.pushViewController(switchTest, animated: true)
        case 12:
            let  PickerView = ElarcPickerViewController()
            PickerView.title = "PickerView"
            self.navigationController?.pushViewController(PickerView, animated: true)
        case 13:
            let BubbleModal = BubbleTransitionTestVC()
            BubbleModal.title = "BubbleModal"
            self.navigationController?.pushViewController(BubbleModal, animated: true)
        case 14:
            let parallaxTestVC = ParallaxTestVC()
            parallaxTestVC.title = "ParallaxTestVC"
            self.navigationController?.pushViewController(parallaxTestVC, animated: true)
        case 15:
            let airPrint = AirPrintTestVc()
            airPrint.title = "airPrint"
            self.navigationController?.pushViewController(airPrint, animated: true)
        case 16:
            let faceDetectVc = FaceDetectVc()
            faceDetectVc.title = "faceDetectVc"
            self.navigationController?.pushViewController(faceDetectVc, animated: true)
            reflectTest(faceDetectVc)
            
        case 17:
            let qRScan = QRScanViewController()
            qRScan.title = "二维码"
            self.navigationController?.pushViewController(qRScan, animated: true)
            
        case 18:
            let pedometer = PedometerViewController()
            pedometer.title = "计步器"
            self.navigationController?.pushViewController(pedometer, animated: true)
        case 19:
            let someTest = ContainerViewController()
            someTest.title = "试验田"
            self.navigationController?.pushViewController(someTest, animated: true)
        default:
            return
        }
    }
    
//    反射测试
    func reflectTest(_class:UIViewController) -> Void {
        //将user对象进行反射
        let hMirror = Mirror(reflecting: _class)
        
        print("对象类型：\(hMirror.subjectType)")
        print("对象子元素个数：\(hMirror.children.count)")
        
        print("--- 对象子元素的属性名和属性值分别如下 ---")
        for case let (label?, value) in hMirror.children {
            print("属性：\(label)     值：\(value)")
        }

        let imageView = getValueByKey(_class, key: "imageView")
//          也可直接用KVC 
//          let imageView = _class.valueForKey("imageView")
//           _class.setValue("elarc", forKey: "imageView")
        
        if imageView is NSNull {
            print("imageView这个属性不存在")
        }else if (imageView as? AnyObject) == nil {
            print("imageView这个属性是个可选类型，且为nil")
        }else if imageView is String {
            print("imageView这个属性String类型，其值为：\(imageView)")
        }
    }
    
    //根据属性名字符串获取属性值
    func getValueByKey(obj:AnyObject, key: String) -> Any {
        let hMirror = Mirror(reflecting: obj)
        for case let (label?, value) in hMirror.children {
            if label == key {
                return unwrap(value)
            }
        }
        return NSNull()
    }
    
    //将可选类型（Optional）拆包
    func unwrap(any:Any) -> Any {
        let mi = Mirror(reflecting: any)
        if mi.displayStyle != .Optional {
            return any
        }
        
        if mi.children.count == 0 { return any }
        let (_, some) = mi.children.first!
        return some
    }
    
    
    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
        let searchIPsVc = SearchIPsViewController()
        let nav = BaseNavigationController(rootViewController: searchIPsVc)
        
        let iconImageView = UIImageView(frame: CGRectMake(UIScreen.mainScreen().bounds.size.width/2 - 50, 100, 100, 100))
        iconImageView.image = UIImage(named: "panda")
        
        let updateTransition: TRPresentTransitionMethod = .Elevate(maskView: iconImageView, to: UIScreen.mainScreen().tr_center)
        tr_presentViewController(nav, method: updateTransition, completion: {
            print("Present finished.")
        })
    
//        nav.transitioningDelegate = searchViewControllerTransition
//        nav.modalPresentationStyle = UIModalPresentationStyle.Custom
//        statusBarStyle: presentViewController(nav, animated: true) { () -> Void in
//        }
        return false
    }
    func buildTableViewheader(){
        
        let imageArray:[String] = ["01","02"]
        var imageNameS:[String] = []
        #if DEVELOPMENT
            imageNameS = imageArray.reverse()
        #else
            imageNameS = imageArray
        #endif
        
        let iconImageView = UIImageView(frame: CGRectMake(UIScreen.mainScreen().bounds.size.width/2 - 50, 100, 100, 100))
        iconImageView.image = UIImage(named: imageNameS[0])
        Animations.showAnimationWithLeftToRight(iconImageView)
        let headerView = ZoomTableHeaderView(tableview: tableView, height: 300, image: UIImage(named: imageNameS[1]), customTopView: iconImageView)
        tableView.zoomHeaderView = headerView
        tableView.showBlurImageWhenScroll = true
        
    }
    
     func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }
    
    //录音功能

    var recorder:AVAudioRecorder? //录音器
    var player:AVAudioPlayer? //播放器
    var recorderSeetingsDic:[String:AnyObject]? //录音设置参数数组
    var volumeTimer:NSTimer! //定时器线程，循环监测录音的音量大小
    var aacPath:String? //录音存储路径
    var volumStr:String = "" //显示录音音量
     let segView = UISegmentedControl(items: ["录音","录制结束","播放声音","音量"])
     func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        vidioCreate()
        segView.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 40)
        segView.backgroundColor = UIColor.randomColor()
        segView.addTarget(self, action: #selector(segmentedControlTouch), forControlEvents: .ValueChanged)
        return segView
    }
    
    func vidioCreate() -> Void {
        
         //初始化录音器
        let session:AVAudioSession = AVAudioSession.sharedInstance()
        //设置录音类型
        try! session.setCategory(AVAudioSessionCategoryPlayAndRecord)
        //设置支持后台
        try! session.setActive(true)
        //获取Document目录
        let docDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
                                                         .UserDomainMask, true)[0]
        //组合录音文件路径
        aacPath = docDir + "/play.aac"
        //初始化字典并添加设置参数
        recorderSeetingsDic =
            [
                AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatMPEG4AAC),
                AVNumberOfChannelsKey: 2, //录音的声道数，立体声为双声道
                AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue,
                AVEncoderBitRateKey : 320000,
                AVSampleRateKey : 44100.0 //录音器每秒采集的录音样本数
        ]

        
    }
    
    func segmentedControlTouch(sender: UISegmentedControl) -> Void{
        
        switch sender.selectedSegmentIndex {
        case 0:
            if sender.selected == false {
              startRecord()
            }
        case 1:
            if sender.selected == false {
              finishRecord()
            }
        case 2:
            if sender.selected == false {
              playRecord()
            }
        default:
            break
        }
        
    }
    
    func startRecord() -> Void {
        //初始化录音器
        recorder = try! AVAudioRecorder(URL: NSURL(string: aacPath!)!,
                                        settings: recorderSeetingsDic!)
        if recorder != nil {
            //开启仪表计数功能
            recorder!.meteringEnabled = true
            //准备录音
            recorder!.prepareToRecord()
            //开始录音
            recorder!.record()
            //启动定时器，定时更新录音音量
            volumeTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self,
                                                                 selector: #selector(IPTableViewController.levelTimer), userInfo: nil, repeats: true)
        }

    }
    
    func finishRecord() -> Void {
        //停止录音
        recorder?.stop()
        //录音器释放
        recorder = nil
        //暂停定时器
        volumeTimer.invalidate()
        volumeTimer = nil
        volumStr = "录音音量:0"
        segView.setTitle(volumStr, forSegmentAtIndex: 3)
    }
    
    func playRecord() -> Void {
        //播放
        player = try! AVAudioPlayer(contentsOfURL: NSURL(string: aacPath!)!)
        if player == nil {
            print("播放失败")
        }else{
            player?.play()
        }

    }
    
    //定时检测录音音量
    func levelTimer(){
        recorder!.updateMeters() // 刷新音量数据
        _ = recorder!.averagePowerForChannel(0) //获取音量的平均值
        let maxV:Float = recorder!.peakPowerForChannel(0) //获取音量最大值
        let lowPassResult:Double = pow(Double(10), Double(0.05*maxV))
        volumStr = "音量:\(lowPassResult)"
        segView.setTitle(volumStr, forSegmentAtIndex: 3)
    }

    
//表格支持复制功能
    func tableView(tableView: UITableView, performAction action: Selector,
        forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
            let board = UIPasteboard.generalPasteboard()
            board.string = dataArray[indexPath.row] as? String
    }
    
    func tableView(tableView: UITableView, canPerformAction action: Selector,
        forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
            if action == #selector(NSObject.copy(_:)) {
                return true
            }
            return false
    }
    
    func tableView(tableView: UITableView,
        shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
            return true
    }
}
